import { useEffect } from "react";
import TWEEN from "@tweenjs/tween.js";
import { useFrame } from "@react-three/fiber";
let time = 0;
export default function Director({ data, camera, rocket, bus }: any) {
  useEffect(() => {
    new TWEEN.Tween(data.current.camera)
      .to([0, -0.5, 0.5], 3000)
      .easing(TWEEN.Easing.Quadratic.Out)
      .start();
    bus.current.addEventListener("start", () => {
      new TWEEN.Tween(data.current.camera)
        .to([0, 0, 1.5], 1500)
        .easing(TWEEN.Easing.Quadratic.InOut)
        .start()
        .onComplete(() => {
          bus.current.dispatchEvent({ type: "startBoost" });
          data.current.start = true;
        });
    });
  }, []);

  useFrame(({ clock }) => {
    TWEEN.update();
    const now = clock.elapsedTime;
    const dt = now - time;
    bus.current.dispatchEvent({ type: "update", time: now, dt });
    if (data.current.start) {
      data.current.camera[1] = rocket.current.position.y;
      data.current.camera[2] = rocket.current.position.z + 1.5;
    }
    camera.current.position.set(...data.current.camera);
    camera.current.lookAt(rocket.current.position);
    time = now;
  });
  return null;
}
